package com.lyon.custom.server.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.lyon.custom.api.model.*;
import com.lyon.custom.server.service.ConfigCacheService;
import com.lyon.custom.server.service.LongPollingService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LeeYan9
 * @since 2021-11-29
 */
@RestController
@RequestMapping("/v1/config/server")
@Validated
public class ConfigServerController {

    @Resource
    LongPollingService longPollingService;

    @GetMapping
    public CommonResult getConfig(HttpServletResponse response, @Validated ConfigBaseReqVO configBaseReqVO) {
        String content = ConfigCacheService.getContent(configBaseReqVO.getTenantId(), configBaseReqVO.getGroup(), configBaseReqVO.getDataId());
        response.setHeader("CONFIG-TYPE", ConfigCacheService.getContentType(configBaseReqVO.getTenantId(), configBaseReqVO.getGroup(), configBaseReqVO.getDataId()));
        return CommonResult.success(content);
    }

    @PostMapping
    public CommonResult publishConfig(@Validated @RequestBody ConfigPublishReqVO configPublishReqVO) {
        longPollingService.publishConfig(configPublishReqVO);
        return CommonResult.success();
    }

    @PostMapping("/listener")
    public void getConfig(HttpServletRequest request, HttpServletResponse response, @RequestBody @Validated ConfigListenerReqVO configListenerReqVO) {
        // 同步逻辑..
        if (configListenerReqVO.getSync()) {
            // 直接比较md5 返回发生变更的id;
            List<String> changeGroupKeys = new ArrayList<>();
            configListenerReqVO.getClientMd5Map().forEach((groupKey, clientMd5) -> {
                if (!ConfigCacheService.isUptodate(groupKey, clientMd5, null, null)) {
                    changeGroupKeys.add(groupKey);
                }
            });
            ServletUtil.write(response, JSONUtil.toJsonStr(changeGroupKeys), ContentType.JSON.getValue());
        }
        // 长轮询
        ConfigListenerReqBO listenerReqBO = BeanUtil.copyProperties(configListenerReqVO, ConfigListenerReqBO.class);
        longPollingService.doPollingClient(listenerReqBO.setRequest(request).setResponse(response));
    }

}
